<template>
  <div>
    <div class="wTags-area">
      <template v-for="(item, index) in tagsList">
        <div
          class="wTags-item"
          :class="{ wActive: isActive(item.path) }"
          :key="index"
        >
          <router-link :to="item.path" class="wTags-title">{{
            item.title
          }}</router-link>
          <span class="wTags-icon" @click="closeTags(index)" v-if="index != 0">
            <i class="el-icon-close"></i>
          </span>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tagsList: [
        // 默认显示系统首页，且不能被删除，永远保持在第一位
        {
          title: "系统首页",
          path: "/admin/index",
          name: "index",
        },
      ],
    };
  },
  methods: {
    // 根据路径显示当前选择
    isActive(path) {
      return path === this.$route.path;
    },
    // 设置标签
    setTags(route) {
      const isExist = this.tagsList.some((item) => {
        return item.path === route.path;
      });
      if (!isExist) {
        if (this.tagsList.length >= 8) {
          this.tagsList.splice(1, 1); // 删除第二个元素，默认第一个是系统首页
        }
        this.tagsList.push({
          title: route.meta.title,
          path: route.path,
          name: route.matched[1].components.default.name,
        });
      }
      // 更新 store 中的 tags 数组
      this.$store.commit("tagsList", this.tagsList);
    },
    // 关闭单个标签
    closeTags(index) {
      const delItem = this.tagsList.splice(index, 1)[0];
      const item = this.tagsList[index]
        ? this.tagsList[index]
        : this.tagsList[index - 1];
      if (item) {
        delItem.path === this.$route.path && this.$router.push(item.path);
      } else {
        this.$router.push("/");
      }
    },
  },
  watch: {
    $route(newValue, oldValue) {
      this.setTags(newValue);
    },
  },
  created() {
    // 设置标签
    this.setTags(this.$route);
  },
};
</script>

<style lang="less">
@import "~@/assets/css/publicStyle.less";
.wTags-area {
  position: absolute;
  width: 100%;
  height: 30px;
  z-index: 2;
  background-color: #ffffff;
  box-shadow: 0 5px 5px 1px #ddd;
  overflow: hidden;
  display: flex;
  align-items: center;

  .wTags-item {
    float: left;
    margin: 3px 5px 2px 3px;
    border-radius: 3px;
    font-size: 12px;
    overflow: hidden;
    cursor: pointer;
    height: 23px;
    line-height: 23px;
    border: 1px solid #e9eaec;
    background: #fff;
    padding: 0 5px 0 12px;
    vertical-align: middle;
    color: #666;
    -webkit-transition: all 0.3s ease-in;
    -moz-transition: all 0.3s ease-in;
    transition: all 0.3s ease-in;

    &.wActive {
      border: 1px solid #409eff;
      background-color: #409eff;
      color: #ffffff;
      .wTags-title {
        color: #ffffff;
      }
    }

    .wTags-title {
      float: left;
      max-width: 80px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 5px;
      color: #666;
    }
  }
}
</style>